<?php

namespace app\api\controller;

use think\facade\Config;
use app\api\controller\Base;
use app\goods\model\ImsEweiShopGoods;
use app\member\model\ImsEweiShopMemberAddress;
use app\member\model\ImsMcMembers;
use app\member\model\ImsEweiShopMember;
use app\member\model\ImsEweiShopMemberCart;
use app\order\model\ImsEweiShopOrder;
use app\order\model\ImsEweiShopOrderGoods;
use app\wechat\service\PaymentService;
use app\wechat\service\WechatService;
use EasyWeChat\Foundation\Application;
use app\activityNew\model\ImsEweiShopActivity;
use app\wechat\model\WechatPaymentRecord;
use app\wechat\model\WechatPaymentRefund;

class Notify extends Base
{
    public function index()
    {
    	$input = file_get_contents('php://input');
    	error_log('INPUT_DATA'.$input);
    	$signature = $this->request->get('signature');
    	$echostr = $this->request->get('echostr');
    	$timestamp = $this->request->get('timestamp');
    	$nonce = $this->request->get('nonce');
    	error_log('TUISONG_DATA-'.$signature.'--'.$echostr.'--'.$timestamp.'--'.$nonce);
    	$inputArr = [];
    	if (!empty($input)) {
    		$inputArr = json_decode($input,true);
    	}
    	if (!empty($inputArr) && isset($inputArr['Event']) && $inputArr['Event'] == 'retail_pay_notify') {
    		// 支付回调
    		if (isset($inputArr['pay_status']) && $inputArr['pay_status'] == 'ORDER_PAY_SUCC') {
    			// 支付成功
                $extra = [
                    'openid'         => $inputArr['payer_openid'] ?? null,
                    'payment_bank'   => isset($inputArr['bank_type'])?$inputArr['bank_type']:'OTHERS',
                    'payment_time'   => date('Y-m-d H:i:s', strtotime($inputArr['pay_time'])),
                    'payment_remark' => $inputArr['pay_status'] ==  "ORDER_PAY_SUCC"? '支付成功': null,
                    'payment_notify' => json_encode($inputArr, 64 | 256),
                ];
                $this->updatePaymentActionB2b($inputArr['out_trade_no'],$inputArr['wxpay_transaction_id'],$inputArr['amount']['payer_amount']/100,$extra);
    		}else{
    			error_log('ORDER_PAY_ERROR'.json_encode($inputArr,JSON_UNESCAPED_UNICODE));
    		}

    	}
        else{
           $this->NotifyPaymentB2bRefundAction($inputArr);
        }

    }

    /**
     * 更新创建支付行为
     * @param string $pCode 商户订单单号
     * @param string $pTrade 平台交易单号
     * @param string $pAmount 实际到账金额
     * @param array $extra 订单扩展数据
     * @return boolean|array
     */
    protected function updatePaymentActionB2b(string $pCode, string $pTrade, string $pAmount, array $extra = [])
    {
        // 更新支付记录
        $model = WechatPaymentRecord::mk()->where(['code' => $pCode])->findOrEmpty();
        if ($model->isEmpty()) return false;
        // 更新支付行为
        foreach ($extra as $k => $v) if (is_null($v)) unset($extra[$k]);
        $model->save($extra + ['payment_trade' => $pTrade, 'payment_status' => 1, 'payment_amount' => $pAmount]);
        // 更新订单
        $record = $model->toArray();
        $modelOrder = ImsEweiShopOrder::mk()->where(['ordersn' => $record['order_code']])->findOrEmpty();
        if ($modelOrder->isEmpty()) return false;
        error_log('updatePaymentActionOrder-----'.json_encode($modelOrder->toArray(), JSON_UNESCAPED_UNICODE));
        $modelOrder->save(['status' => 1, 'paytype' => 21, 'paytime' => time(),'transid'=>$pTrade]);
        ImsEweiShopOrder::afterPayOrder($record['order_code']);
        return true;
    }

    /**
     * @return void退款通知消息
     */
    protected function NotifyPaymentB2bRefundAction($inputArr)
    {

        if (!empty($inputArr) && isset($inputArr['Event']) && $inputArr['Event'] == 'retail_refund_notify') {
            error_log('ORDER_REFUND_ERROR'.json_encode($inputArr,JSON_UNESCAPED_UNICODE));
            // 支付回调
            if (isset($inputArr['refund_status']) && $inputArr['refund_status'] == 'REFUND_SUCC') {

                $this->updatePaymentB2bRefundOrder($inputArr['out_refund_no'],$inputArr['wxpay_refund_id'],$inputArr['refund_amount']/100,$inputArr);
            }
        }
    }

    /**
     * @return void
     * 更新退款订单信息
     */
    protected function updatePaymentB2bRefundOrder($out_refund_no,$wxpay_refund_id,$payAmount,$inputArr)
    {
        $map = ['code' => $out_refund_no];
        $model = WechatPaymentRefund::mk()->where($map)->findOrEmpty();
        if ($model->isEmpty()) return false;
        $updateData['refund_amount']=$inputArr['refund_amount']/100;
        $updateData['refund_notify']=json_encode($inputArr,64 | 256);
        $updateData['refund_remark']=$inputArr['refund_status'] ==  "REFUND_SUCC"? '退款成功': null;
        $updateData['refund_trade']=$wxpay_refund_id;
        $updateData['refund_status']=1;
        $updateData['refund_time']=$inputArr['refund_time'];

        $model->save($updateData);
//        /**
//         * 更新订单退款金额
//         */

        $recordinfo = WechatPaymentRecord::mk()->where('code','=',$model['record_code'])->findOrEmpty();
        if($recordinfo->isEmpty()) return false;



        $modelOrder = ImsEweiShopOrder::mk()->where(['ordersn'=>$recordinfo['order_code']])->findOrEmpty();
        if($modelOrder->isEmpty()) return false;
        $orderId=$modelOrder['id'];
        $refundAmount=$payAmount['refund_amount'];
        $orderAmount=$inputArr['order_amount'];
        //退款金额大于等支付金额则关闭订单
        if($refundAmount >=$orderAmount){
            $orderUpData['status']=-1;//已关闭订单
            $orderUpData['refund_amount']=$orderAmount/100;
            ImsEweiShopOrder::mk()->where(['id'=>$orderId])->update($orderUpData);
        }
        else{
            ImsEweiShopOrder::mk()->where(['id'=>$orderId])->update(['refund_amount'=>$payAmount+$modelOrder['refund_amount']]);
        }

        //$modelOrder->save(['refundid' => $model->id, 'paytype' => 21, 'paytime' => time(),'transid'=>$pTrade]);
    }

}